<template>
	<view class="task-list">
		<view class="search-bar">
			<uni-data-select v-model="searchParams.status" :localdata="statusOptions" placeholder="任务状态"
				@change="handleSearch" />
			<uni-data-select v-model="searchParams.maintainerId" :localdata="maintainerOptions" placeholder="维护人员"
				@change="handleSearch" />
			<uni-data-select v-model="searchParams.priority" :localdata="priorityOptions" placeholder="优先级"
				@change="handleSearch" />
		</view>

		<uni-card v-for="task in tasks" :key="task.id" :title="task.maintenanceType" :extra="task.status"
			@click="goToDetail(task.id)">
			<view class="task-info">
				<view class="info-row">
					<text class="label">电梯：</text>
					<text class="value" v-if="task.elevator">
						{{task.elevator.building}} - {{task.elevator.location}}
					</text>
					<text class="value" v-else>未指定</text>
				</view>
				<view class="info-row">
					<text class="label">维护人：</text>
					<text class="value">{{task.maintainer ? task.maintainer.username : '未指定'}}</text>
				</view>
				<view class="info-row">
					<text class="label">开始时间：</text>
					<text class="value">{{task.startTime}}</text>
				</view>
				<view class="info-row">
					<text class="label">预计时长：</text>
					<text class="value">{{task.estimatedDuration}}小时</text>
				</view>
				<view class="info-row">
					<text class="label">描述：</text>
					<text class="value">{{task.description}}</text>
				</view>
			</view>

			<template v-slot:actions>
				<view class="actions">
					<button class="action-btn" @click.stop="updateStatus(task.id)"
						:class="task.status && task.status.toLowerCase()">
						{{getStatusActionText(task.status)}}
					</button>
					<button class="action-btn" @click.stop="goToEdit(task.id)">
						编辑
					</button>
					<button class="action-btn delete" @click.stop="handleDelete(task.id)">
						删除
					</button>
				</view>
			</template>
		</uni-card>

		<uni-fab :pattern="fabPattern" :content="fabContent" horizontal="right" vertical="bottom"
			@trigger="handleFabClick" />
	</view>
</template>

<script>
	import {
		request
	} from '@/utils/request'

	export default {
		data() {
			return {
				tasks: [],
				searchParams: {
					status: '',
					maintainerId: '',
					priority: ''
				},
				statusOptions: [{
						value: '',
						text: '全部状态'
					},
					{
						value: 'PENDING',
						text: '待处理'
					},
					{
						value: 'IN_PROGRESS',
						text: '进行中'
					},
					{
						value: 'COMPLETED',
						text: '已完成'
					},
					{
						value: 'CANCELLED',
						text: '已取消'
					}
				],
				maintainerOptions: [{
					value: '',
					text: '全部人员'
				}],
				priorityOptions: [{
						value: '',
						text: '全部优先级'
					},
					{
						value: 1,
						text: '低'
					},
					{
						value: 2,
						text: '中'
					},
					{
						value: 3,
						text: '高'
					}
				],
				fabPattern: {
					color: '#007AFF',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF'
				},
				fabContent: [{
					iconPath: '/static/plus.png',
					selectedIconPath: '/static/plus.png',
					text: '新建任务',
					active: false
				}]
			}
		},

		onShow() {
			this.loadMaintainers()
			this.loadTasks()
		},

		methods: {
			async loadMaintainers() {
				try {
					const users = await request({
						url: '/api/users',
						data: {
							role: 'MAINTAINER'
						}
					})

					if (Array.isArray(users)) {
						this.maintainerOptions = [
							{ value: '', text: '全部人员' },
							...users.map(user => ({
								value: user.id,
								text: user.username
							}))
						]
					} else {
						console.error('Unexpected response format for maintainers:', users)
						uni.showToast({
							title: '加载维护人员失败',
							icon: 'none'
						})
					}
				} catch (err) {
					console.error('Failed to load maintainers:', err)
					uni.showToast({
						title: '加载维护人员失败',
						icon: 'none'
					})
				}
			},

			async loadTasks() {
				try {
					const res = await request({
						url: '/api/tasks',
						// data: this.searchParams
					})
					this.tasks = res
				} catch (err) {
					uni.showToast({
						title: '加载任务列表失败',
						icon: 'none'
					})
				}
			},

			handleSearch() {
				this.loadTasks()
			},

			getStatusActionText(status) {
				switch (status) {
					case 'PENDING':
						return '开始'
					case 'IN_PROGRESS':
						return '完成'
					case 'COMPLETED':
						return '重开'
					case 'CANCELLED':
						return '重开'
					default:
						return '更新状态'
				}
			},

			async updateStatus(id) {
				try {
					const task = this.tasks.find(t => t.id === id)
					if (!task) return

					let newStatus
					switch (task.status) {
						case 'PENDING':
							newStatus = 'IN_PROGRESS';
							break
						case 'IN_PROGRESS':
							newStatus = 'COMPLETED';
							break
						case 'COMPLETED':
							newStatus = 'PENDING';
							break
						case 'CANCELLED':
							newStatus = 'PENDING';
							break
					}

					await request({
						url: `/tasks/${id}/status`,
						method: 'PUT',
						data: {
							status: newStatus
						}
					})

					uni.showToast({
						title: '状态更新成功',
						icon: 'success'
					})

					this.loadTasks()
				} catch (err) {
					uni.showToast({
						title: '状态更新失败',
						icon: 'none'
					})
				}
			},

			async handleDelete(id) {
				uni.showModal({
					title: '确认删除',
					content: '是否确认删除该任务？',
					success: async (res) => {
						if (res.confirm) {
							try {
								await request({
									url: `/tasks/${id}`,
									method: 'DELETE'
								})

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})

								this.loadTasks()
							} catch (err) {
								uni.showToast({
									title: '删除失败',
									icon: 'none'
								})
							}
						}
					}
				})
			},

			goToDetail(id) {
				uni.navigateTo({
					url: `/pages/task/detail/index?id=${id}`
				})
			},

			goToEdit(id) {
				uni.navigateTo({
					url: `/pages/task/edit/index?id=${id}`
				})
			},

			handleFabClick() {
				uni.navigateTo({
					url: '/pages/task/create/index'
				})
			}
		}
	}
</script>

<style>
	.task-list {
		padding: 15px;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.search-bar {
		display: flex;
		align-items: center;
		margin-bottom: 15px;
		gap: 10px;
	}

	.task-info {
		padding: 10px 0;
	}

	.info-row {
		display: flex;
		margin-bottom: 8px;
	}

	.label {
		color: #666;
		width: 80px;
		flex-shrink: 0;
	}

	.value {
		flex: 1;
	}

	.actions {
		display: flex;
		justify-content: flex-end;
		gap: 10px;
	}

	.action-btn {
		font-size: 14px;
		padding: 4px 12px;
		border-radius: 4px;
		background-color: #007AFF;
		color: #fff;
	}

	.action-btn.pending {
		background-color: #ff9900;
	}

	.action-btn.in_progress {
		background-color: #007AFF;
	}

	.action-btn.completed {
		background-color: #4cd964;
	}

	.action-btn.cancelled {
		background-color: #8e8e93;
	}

	.action-btn.delete {
		background-color: #ff3b30;
	}
</style>